package socket.tcp.multServer;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;

/**
 * @description: 类描述
 * @author: Fesine
 * @createTime:2016/9/29 23:02
 * @update:修改内容
 * @author: Fesine
 * @updateTime:2016/9/29 23:02
 */
public class ServerThread extends Thread {
    //和本线程相差的socket
    Socket socket;

    public ServerThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        InputStream is=null;
        InputStreamReader isr=null;
        BufferedReader bf=null;
        OutputStream os=null;
        PrintWriter ps=null;
        try {
            //3、获取输入字节流
            is = socket.getInputStream();
            //4、获取字符流
            isr = new InputStreamReader(is);
            //5、封装成缓冲流
            bf = new BufferedReader(isr);
            String data ;
            String username=null;
            while ((data = bf.readLine()) != null) {
                System.out.println("我是服务器，客户端：" + data);
                username = data.split(";")[0].split(":")[1];
            }
            //关闭输入流
            socket.shutdownInput();
            //打开输出字节流，向客户端输出响应信息
            os = socket.getOutputStream();
            //包装成打印流
            ps = new PrintWriter(os);
            ps.write("---->欢迎您!"+ username);
            //获取客户端主机信息
            InetAddress address = socket.getInetAddress();
            System.out.println("---->客户端IP:"+address.getHostAddress());
            ps.flush();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            try {
                if (ps != null) {
                    ps.close();
                }
                if (os != null) {
                    os.close();
                }
                if (bf != null) {
                    bf.close();
                }
                if (isr != null) {
                    isr.close();
                }
                if (is != null) {
                    is.close();
                }
                if (socket != null) {
                    socket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
